<?php
/**
 * Created by PhpStorm.
 * User: jyh
 * Date: 2020/3/22
 * Time: 20:31
 */

namespace app\home\controller;

use app\home\model\SystemLog;
use app\common\controller\Backend;
use think\Db;

/**
 * @title 增删改bug
 * @description 接口说明
 * @group 后台管理
 */
class ProjectBug extends Backend
{
    protected $hsModel = 'ProjectBug';
    protected $projectName = [
        'project_id' => [
            'name' => '所属项目',
            'table' => 'project'
        ],
        'product_id' => [
            'name' => '所属产品',
            'table' => 'project'
        ],
        'versions_id' => [
            'name' => '所属版本',
            'table' => 'versions'
        ],
        'block_id' => [
            'name' => '所属模块',
            'table' => 'block'
        ],
        'need_id' => [
            'name' => '相关需求',
            'table' => 'projectNeed'
        ],
        'assigner' => [
            'name' => '重新指派',
            'table' => 'user',
            'option' => 1
        ],
        'type' => [
            'name' => 'Bug类型',
            'table' => 'deploy'
        ],
        'cause' => [
            'name' => '不予解决',
            'table' => ''
        ],
        'degree' => [
            'name' => '严重程度',
            'table' => ''
        ],
        'system' => [
            'name' => '操作系统',
            'table' => 'deploy'
        ],
        'priority' => [
            'name' => '优先级',
            'table' => ''
        ],
        'browser' => [
            'name' => '浏览器',
            'table' => 'deploy'
        ],
        'title' => [
            'name' => 'Bug标题',
            'table' => ''
        ],
        'describe' => [
            'name' => 'Bug详情',
            'table' => ''
        ],
        'etime' => [
            'name' => '截至日期',
            'table' => ''
        ],
        'status' => [
            'name' => '',
            'table' => '',
            'option' => 2
        ],
    ];
    /**
     * @title 查看bug
     * @description 接口说明
     * @author jyh
     * @url /ProjectBug/query/:id
     * @method POST
     */
    public function query($id)
    {
        if ( !isset($id) ) {
            return json(['code' => 0, 'msg' => '缺少必要参数']);
        }

        if ( $this->request->isPost() ) {
            $map = $this->request->post();
            $page = (int)input('page', 1);
            $limit = (int)input('limit', 10);
            // 判断是否有条件
            if (empty($map)) {
                $data = Db::name($this->hsModel)->where('id', $id)->find();
                if ($data['need_id'] != 0) {
                    $data['name'] = Db::name('ProjectNeed')->where('id', $data['need_id'])->value('name');
                }

                $data['isself'] = $data['assigner'] == USER_ID ? true : false;
                $data['isauth'] = !in_array(USER_DEPT,[0,1]) ? true : false;
                $data['time'] = $data['etime'] ? date('Y-m-d', $data['etime']) : '';
            } else {
                $where = [];
                $like = '';
                // 循环把空的数据删除
                foreach ($map as $key => $value) {
                    if ($value === '') unset($map[$key]);
                }
                if (isset($map['project_id'])) {
                    $where['pb.project_id'] = $map['project_id'];
                } else if (isset($map['product_id'])) {
                    $where['pb.product_id'] = $map['product_id'];
                    if (isset($map['versions_id'])) $where['pb.versions_id'] = $map['versions_id'];
                } else {
                    $where['pb.issue_id'] = isset($map['issue_id']) ? $map['issue_id'] : Db::name('IssueVersions')->order('ctime','desc')->value('id');
                }
                if (isset($map['status'])) $where['pb.status'] = $map['status'];
                if (isset($map['type'])) $where['pb.type'] = $map['type'];
                if (isset($map['degree'])) $where['pb.degree'] = $map['degree'];
                if (isset($map['priority'])) $where['pb.priority'] = (int)$map['priority'];
                if (isset($map['assigner'])) $where['pb.assigner'] = $map['assigner'];
                if (isset($map['keywords'])) $like = "pb.id like '%{$map['keywords']}%' OR pb.title like '%{$map['keywords']}%' OR pb.describe like '%{$map['keywords']}%' OR p.name like '%{$map['keywords']}%'";
                $data = $this->model()
                    ->alias('pb')
                    ->join('Project p', 'pb.product_id = p.id', 'left')
                    ->where($where)
                    ->where('pb.deleted', 'null')
                    ->where($like)
                    ->field('pb.id,pb.status,pb.type,pb.priority,pb.product_id,pb.title,pb.degree,pb.assigner,pb.creator,pb.etime,pb.ctime')
                    ->order('pb.ctime', 'desc')
                    ->paginate([
                        'page' => $page,
                        'list_rows' => $limit,
                    ], false);

                foreach ($data as $key => $value) {
                    $data[$key]['isself'] = $data[$key]['assigner'] == USER_NAME ? true : false;
                    $data[$key]['isauth'] = !in_array(USER_DEPT,[0,1]) ? true : false;
                }
            }

            return json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
        }
    }

    /**
     * @title 获取首页bug数据
     * @description 接口说明
     * @author jyh
     * @url /ProjectBug/getIndexBug
     * @method POST
     */
    public function getIndexBug()
    {
        $model = $this->model();
        $where = [];
        // 是前端或后端则加此条件
        if (USER_DEPT == 0 || USER_DEPT == 1) {
            $where['assigner'] = USER_ID;
        }
        $data = $model->where('deleted','null')->where($where)->where('status','<>',3)->order('ctime','desc')->select();

        if ( empty($data) ) {
            return json(['code' => 0,'msg' => '暂无数据']);
        }
        return json(['code' => 0, 'msg' => '成功','data' => $data]);
    }

    /**
     * @title 新增bug
     * @description 接口说明
     * @author jyh
     * @url /projectBug/add
     * @method POST
     * @param name:project_id type:int require:1 default: other: desc:项目id
     * @param name:product_id type:int require:1 default: other: desc:产品id
     * @param name:versions_id type:int require:1 default: other: desc:版本id
     * @param name:block_id type:int require:1 default: other: desc:模块id
     * @param name:assigner type:int require:1 default: other: desc:Bug指派
     * @param name:etime type:int require:1 default: other: desc:截止日期
     * @param name:degree type:int require:1 default: other: desc:严重程度
     * @param name:priority type:int require:1 default: other: desc:优先级
     * @param name:type type:string require:1 default: other: desc:bug类型
     * @param name:title type:string require:1 default: other: desc:bug标题
     * @param name:describe type:string require:1 default: other: desc:bug详情
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (isset($params['need_id'])) {
                Db::table('hs_project_need')->where('id', $params['need_id'])->update(['status' => 4]);
            }
        }
        return parent::add(); // TODO: Change the autogenerated stub
    }

    /**
     * @title 删除bug
     * @author jyh
     * @url /projectBug/del/:id
     * @method POST
     * @param name:id type:int require:1 default: other: desc:项目id
     */
    public function del($ids = "")
    {
        return parent::del($ids); // TODO: Change the autogenerated stub
    }

    /**
     * @title 修改bug
     * @description 接口说明
     * @author jyh
     * @url /projectBug/edit/:id
     * @method POST
     * @param name:id type:int require:1 default: other: desc:项目id
     */
    public function edit($ids = "")
    {
        // 记录修改日记
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $this->recordLog($ids,$params);
            if (isset($params['status'])) {
                $result = $this->model()->where('id',$ids)->update(['status' => $params['status']]);
                if ($result < 1) return json(['code' => 1, 'msg' => '状态修改失败']);
                // 拿到相关需求
                $need_id = $this->model()->where('id',$ids)->value('need_id');
                // 检测是否还有未关闭的bug
                $res = Db::name('projectBug')
                    ->where('need_id',$need_id)
                    ->where('status', '<>',3)
                    ->value('id');
                // 3=已关闭 4=激活
                switch ($params['status']) {
                    case 3:
                        if (!$res) Db::name('projectNeed')->where('id',$need_id)->update(['status' => 5]);
                    break;
                    case 4:
                        if ($res) Db::name('projectNeed')->where('id',$need_id)->update(['status' => 4]);
                    break;
                }
            }
        }
        return parent::edit($ids);
    }

    /**
     * @title 记录bug日记
     * @description 接口说明
     * @author jyh
     */
    protected function recordLog($id,$nowData)
    {
        $data = Db::name('ProjectBug')->where('id',$id)->find();
        if (isset($nowData['etime'])) {
            $data['etime'] = $data['etime'] ? date('Y-m-d',$data['etime']) : '';
            $nowData['etime'] = $data['etime'] ? date('Y-m-d',$nowData['etime']) : '';
        }
        if (isset($nowData['ptime'])) {
            $data['ptime'] = $data['ptime'] ? date('Y-m-d',$data['ptime']) : '';
            $nowData['ptime'] = $nowData['ptime'] ? date('Y-m-d',$nowData['ptime']) : '';
        }
        $statusName = [1 => '已确认', 2 => '已解决',3 => '已关闭', 4 => '激活'];
        if (isset($nowData['status'])) {
            $this->projectName['status']['name'] = $statusName[$nowData['status']];
        }
        $log = [];
        foreach ($this->projectName as $key => $value) {
            if (!isset($nowData[$key])) continue;
            if ($nowData[$key] != $data[$key]) {
                $log[$key]['uid'] = USER_ID;
                $log[$key]['uname'] = USER_NAME;
                $log[$key]['need_id'] = $id;
                $log[$key]['title'] = $value['name'];
                $log[$key]['mfront'] = $value['table'] == '' ? $data[$key] : Db::name($value['table'])->where('id',$data[$key])->value('name');
                $log[$key]['mafter'] = $value['table'] == '' ? $nowData[$key] : Db::name($value['table'])->where('id',$nowData[$key])->value('name');
                $log[$key]['ctime'] = time();
                $log[$key]['option'] = isset($value['option']) ? $value['option'] : 0;
                $log[$key]['status'] = 1;
            }
        }
        $logModel = new SystemLog();
        $log = array_values($log);

        if (!empty($log)) {
            $logModel->insertAll($log);
        }
    }
}